/**
 * Created by zhanglihe on 15/11/10.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'collection',
    'template',
    'model',
    'dialog'
], function ($, common, ready, Collection, template, Model, dialog) {
    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            loading();
            this.fetch();
            this.event();
        },

        fetch: function () {
            var _this = this;
            this.collection = new Collection({
                url: _global.url.api + 'goodss',
                condition: {limit: 10, offset: 0},
                model: {
                    url: _global.url.api + 'goods/{id}',
                    event: {
                        '.item-edit:click': 'edit',
                        '.item-remove:click': 'remove',
                        '.item-on-sale:click': 'onSale',
                        '.item-off-sale:click': 'offSale',
                        '.item-count': 'saleCount',
                        '.item-copy-url': 'copyUrl',
                        '.edit-stock:click': 'editStock'
                    },
                    remove: function (e) {
                        e.preventDefault();
                        var model = this;
                        dialog({
                            'content': '确定删除吗?',
                            ok: function () {
                                model.del();
                            }, cancel: function () {
                            }
                        }).show(e.target);
                    },
                    onSale: function (e) {
                        e.preventDefault();
                        var goods_id = this.data.id;
                        var status = 1;
                        if (new Model({
                                url: _global.url.api + 'goods_status',
                                data: {'goods_id': goods_id, 'status': status}
                            }).put()) {
                        }
                        _this.collection.fetch();
                    },
                    offSale: function (e) {
                        e.preventDefault();
                        var goods_id = this.data.id;
                        var status = 2;
                        if (new Model({
                                url: _global.url.api + 'goods_status',
                                data: {'goods_id': goods_id, 'status': status}
                            }).put()) {
                        }
                        _this.collection.fetch();
                    },
                    saleCount: function (e) {
                        e.preventDefault();
                        var _this = this;
                        $.ajax({
                            url: _global.url.api + 'goods/sale_count/' + this.data.id,
                            type: 'get',
                            success: function (res) {
                                var data = res.data;
                                data.goods_name = _this.data.name;
                                dialog({
                                    content: template('count-tpl', data),
                                    ok: function () {
                                    }
                                }).show(e.target);
                            }
                        });
                    },
                    copyUrl: function (e) {
                        e.preventDefault();
                        dialog({
                            content: this.get_data('wap_url') + '<br>请全选并点右键复制',
                            ok: function () {
                            }
                        }).show(e.target);
                    },
                    editStock: function (e) {
                        e.preventDefault();
                        //console.log(this.data);
                        dialog({
                            title: '编辑库存',
                            content: template('stock-tpl', this.data),

                            ok: function () {
                                var stock_num = $('input[name="stock"]').length;
                                var stock = {};
                                var oldstock = {};
                                for (var i = 0; i < stock_num; i++) {
                                    stock[i] = {
                                        id: $('input[name="stock"]').eq(i).attr('data-id'),
                                        num: $('input[name="stock"]').eq(i).val(),
                                        skumark: $('input[name="stock"]').eq(i).attr('sku-mark'),
                                        oldstock: $('input[name="stock"]').eq(i).attr('data-stock')
                                    };
                                }
                                if (new Model({
                                        url: _global.url.api + 'goods_stock',
                                        data: {'stock': stock, 'oldstock': oldstock}
                                    }).put()) {
                                }
                                _this.collection.fetch();
                            },
                            cancel: function () {
                            }
                        }).show(e.target);
                    }
                },
                callback: function () {
                    loaded();
                }
            });
            this.collection.fetch();
        },

        event: function () {
            var _this = this;
            $('#btn-search').on('click', function (e) {
                e.preventDefault();
                click_search();
            });

            var click_search = function (fun) {
                _this.collection.condition.keyword = $('input[name="keyword"]').val();
                _this.collection.callback = function () {
                    if (fun && fun == 'toExcel') {
                        toExcel();
                        _this.collection.callback = function () {
                        }
                    }
                }
                _this.collection.reload();
            }
            //按照状态查询
            $('#btn-status').find('a').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.keyword = '';
                _this.collection.condition.status = $(e.target).attr('rel');
                _this.collection.reload();
                $(e.target).addClass('active').siblings().removeClass('active');
            });

            //to excel
            var href;
            var toExcelWindow;
            $(".btn-excel").on("click", function (e) {
                e.preventDefault();
                href = $(this).attr('href');
                toExcelWindow = dialog({
                    content: '请稍等 ,正在导出...',
                    width: 200,
                    modal: true
                }).show();
                click_search('toExcel');
            });
            var toExcel = function () {
                toExcelWindow.close();
                console.log(_this.collection.result._count);
                var limit = 1000;
                var params = '';
                var data = _this.collection.condition;
                var total = _this.collection.result._count;

                if (total < 1) {
                    alert('没有需要导出的订单');
                    return false;
                }

                for (var i in data) {
                    if (i == 'limit' || i == 'offset') continue;
                    params = params + '&' + i + '=' + encodeURIComponent(data[i]);
                }
                href = (href.indexOf('?') === -1) ? href + '?' : href;
                href = href + params + '&limit=' + limit + '&offset=';

                if (total > limit) {
                    var showData = {};
                    showData.pages = Math.ceil(total / limit);
                    showData.total = total;
                    showData.limit = limit;
                    showData.href = href;
                    dialog({
                        title: '导出订单列表Excel文件',
                        content: template('to-excel-tpl', showData),
                        width: 600,
                        heigth: 500,
                        modal: true,
                        ok: function () {
                        },
                        cancel: function () {
                        }
                    }).show();
                } else {
                    window.location.href = href;
                }
            }
        }
    }
    ;

    new index();

})
;